#include "hmi_music.h"
#include "cot_menu.h"
#include "key_manager.h"
#include "led_manager.h"
#include <string.h>
#include <stdio.h>

static char sg_volume = 0;
static bool sg_isPlaying = false;

static void OnKeyFunCB(cotKey_t key)
{
    if (cotKey_IsTriggerWayMet(KEY_0, COT_KEY_TRIGGER_WAY_LOSSEN))
    {
        cotMenu_Exit(false);
    }
    if (cotKey_IsTriggerWayMet(KEY_1, COT_KEY_TRIGGER_WAY_LOSSEN))
    {
        sg_isPlaying = !sg_isPlaying;
    }
    if (cotKey_IsTriggerWayMet(KEY_UP, COT_KEY_TRIGGER_WAY_LOSSEN))
    {
        sg_volume++;
        
        if (sg_volume > 16)
        {
            sg_volume = 1;
        }
        
        cotLed_Twinkle(LED_0, sg_volume * 10);
    }
}

void Hmi_MusicEnter(const cotMenuItemInfo_t *ptItemShowInfo)
{

}

void Hmi_MusicLoad(const cotMenuItemInfo_t *ptItemShowInfo)
{
    cotKey_Listen(KEY_0, OnKeyFunCB);
    cotKey_Listen(KEY_1, OnKeyFunCB);
    cotKey_Listen(KEY_UP, OnKeyFunCB);
    
    cotKey_ResetDefaultConfig(KEY_0);
    cotKey_ResetDefaultConfig(KEY_1);
    cotKey_ResetDefaultConfig(KEY_UP);
    
    char buf[20];
    
    snprintf(buf, sizeof(buf), "----%s----", get_text(ptItemShowInfo->uMenuDesc.textId));

    cotLed_Twinkle(LED_0, sg_volume * 10);

    cotOled_Clear(OLED_BLACK);
    cotOled_SetText(0, 0, buf, 0, FONT_16X16);
}

void Hmi_MusicExit(const cotMenuItemInfo_t *ptItemShowInfo)
{
    cotLed_SetState(LED_0, COT_LED_OFF);
}

void Hmi_MusicTask(const cotMenuItemInfo_t *ptItemShowInfo)
{
    if (sg_isPlaying)
    {
        cotOled_SetText(24, 24, get_text(TEXT_BEING_PLAYING), 0, FONT_16X16);
    }
    else
    {
        cotOled_SetText(24, 24, get_text(TEXT_PLAY_STOP), 0, FONT_16X16);
    }
    
    for (int i = 0; i < 16; i++)
    {
        if (i < sg_volume)
        {
            cotOled_SetText(0 + i * 8, 48, "-", 0, FONT_16X16);
        }
        else
        {
            cotOled_SetText(0 + i * 8, 48, " ", 0, FONT_16X16);
        }
    }
}
